using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using DotSVN.Server.RepositoryAccess;
using System.IO;
using System.Web.UI.HtmlControls;

namespace DotSVN.WebSample
{
    public partial class MainView : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // Sample query string  ?rev=30&path=trunk/src/LICENSE.txt
            string path = Request.QueryString["path"];
            ISVNRepository repository = Global.CurrentRepository;

            if (!String.IsNullOrEmpty(path) && repository != null)
            {
                path = path.Trim();
                string revision = Request.QueryString["rev"];
                int revisionNum = -1;
                if( !String.IsNullOrEmpty(revision) )
                {
                    revision = revision.Trim();
                    bool parseFailed = Int32.TryParse(revision, out revisionNum);
                    if(parseFailed)
                        revisionNum = -1;  // Get the Head revision
                }

                IDictionary<string, string> properties = new Dictionary<string, string>();

                MemoryStream outputStream = new MemoryStream(1024 * 1024);
                repository.GetFile(path, revisionNum, properties, outputStream);
                outputStream.SetLength(outputStream.Position);
                outputStream.Seek(0, SeekOrigin.Begin);

                

                StringBuilder contents = new StringBuilder();
                contents.AppendLine("<pre><textarea name=\"code\" class=\"csharp\" cols=\"60\" rows=\"1\">");
                try 
                {
                    // Create an instance of StreamReader to read from a file.
                    using (StreamReader reader = new StreamReader(outputStream))
                    {
                        string line;
                        // Read and display lines from the file until the end of file
                        while ((line = reader.ReadLine()) != null)
                        {
                            contents.AppendLine(line);
                        }
                    }
                }
                catch (Exception ex)
                {
                    contents.AppendLine(ex.Message);
                }
                contents.AppendLine("</textarea></pre>");

                FileContent.InnerHtml = contents.ToString();
            }
        }
    }
}